package com.example.day03_mvp.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public abstract class BaseRlvAdapter<T> extends RecyclerView.Adapter<BaseRlvAdapter.BaseViewHolder> {
    private Context context;
    private List<T> mlist;

    public BaseRlvAdapter(Context context, List<T> mlist) {
        this.context = context;
        this.mlist = mlist;
    }

    private OnItemClickListener onItemClickListener;
    public interface OnItemClickListener{
        void onitemclick(View v,int position);
    }
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(context).inflate(getLayout(), parent, false);
        return new BaseViewHolder(inflate);
    }


    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position, @NonNull List<Object> payloads) {
        T t=mlist.get(position);
        bindData(holder,t);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onItemClickListener!=null){
                    onItemClickListener.onitemclick(view,position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mlist.size();
    }
    //添加更多
    public void addData(List<T> data){
        if (data != null && data.size()>0){
            mlist.addAll(data);
            notifyDataSetChanged();
        }
    }

    //刷新
    public void refreshData(List<T> data){
        if (data != null && data.size()>0){
            mlist.clear();
            mlist.addAll(data);
            notifyDataSetChanged();
        }
    }

    protected abstract void bindData(BaseViewHolder holder, T t);

    protected abstract int getLayout();

    public class BaseViewHolder extends RecyclerView.ViewHolder {
        public BaseViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}
